﻿using System.ComponentModel;
using System.Linq;

namespace DeepEarth.Core
{
    public class LocationTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType)
        {
            return sourceType == typeof(string);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            string locationString = value.ToString();

            string[] parts = locationString.Split(',').Select(s => s.Trim()).ToArray();

            if (!DesignerProperties.IsInDesignTool)
            {
                System.Diagnostics.Debug.Assert(parts.Length == 2);
            }

            bool setLatitude = true;
            bool latitudeHasBeenSet = false;
            double latitude = 0.0, longitude=0.0;

            // If the location is to be set to Latitude:10, Longitude:20, some possible strings are:
            // "10,20"
            // "Latitude = 10, Longitude = 20"
            // "Lon = 20, Lat = 10"
            // "lat = 10, 20"
            foreach (string part in parts)
            {
                string valueString = part;
                string[] namedAxis = part.Split('=').Select(s => s.Trim().ToLower()).ToArray();
                if (namedAxis.Length > 1)
                {
                    valueString = namedAxis[1];

                    if( namedAxis[0].StartsWith("la"))
                    {
                        setLatitude = true;

                        if (latitudeHasBeenSet)
                        {
                            longitude = latitude;
                        }
                    }
                    else
                    {
                        setLatitude = false;
                    }

                }

                if (setLatitude)
                {
                    latitude = double.Parse(valueString);
                    setLatitude = false;
                    latitudeHasBeenSet = true;
                }
                else
                {
                    longitude = double.Parse(valueString);
                    setLatitude = true;
                }
                
            }

            return new Location()
            {
                Latitude = latitude,
                Longitude = longitude
            };

        }
    }
}
